import os

from PIL import Image
from django.db.models import Q

from Wallpaper.models import Wallpaper


def main():
    root = r"E:\Android\Service\MyStation\static\media\staticwallpaper\vertical"
    path_list = os.listdir(path=root)
    i = 0
    for path in path_list:
        path = os.path.join(root, path)
        if not is_valid(path):
            try:
                wallpaper = Wallpaper.objects.get(Q(url__contains=path.rsplit("\\")[-1]))
                wallpaper.delete()
            except:
                pass
            os.remove(path)
            i += 1
            print(path)
    print(i)


def is_valid(file):
    valid = True
    try:
        Image.open(file).load()
    except OSError:
        valid = False
    return valid


if __name__ == "__main__":
    main()
